package com.adee.java;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * https://blog.csdn.net/weigeshikebi/article/details/105776340
 *
 * Collectors.toMap方法在key重复时，如不指定mergeFunction，会抛异常：
 * java.lang.IllegalStateException: Duplicate key a
 */
public class Test048_toMap {
    public static void main1(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("a");
        // 指定mergeFunction为 (oldValue, newValue) -> newValue)
        Map<String, String> map = list.stream().collect(
                Collectors.toMap(a -> a, Function.identity(), (oldValue, newValue) -> newValue));
    }


    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("a");
        // 未指定mergeFunction时，key存在重复时，会抛异常：java.lang.IllegalStateException: Duplicate key a
        Map<String, String> map = list.stream().collect(
                Collectors.toMap(a -> a, Function.identity()));
    }
}
